from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework.views import APIView

from goods.models import SKU
# from orders.serializers import CartSKUSerializer, PlaceOrderSerialzier, OrderSerializer
# <<<<<<< HEAD
from orders.models import OrderGoods, OrderInfo
from orders.serializers import PlaceOrderSerialzier, OrderSerializer, AllGoodsSerializer, AllOrderInfoSerializer, \
    AllOrderGoodsSerializer,CreateCommentSerializer, SkuUpdateSerializer,\
    CommentOrderGoodsSerializer
# =======
from orders.serializers import PlaceOrderSerialzier, OrderSerializer
# >>>>>>> origin/lijianhao

"""
提交订单界面的展示

需求:
    1.必须是登陆用户才可以访问此界面(用户地址信息确定的)
    当登陆用户访问此界面的时候,需要让前端将用户信息传递给后端

思路:
    # 1.接收用户信息,并验证用户信息
    # 2.根据用户信息获取redis中选中商品的id  [id,id,id]
    # 3.根据id获取商品的详细信息 [sku,sku,sku]
    # 4.将对象列表转换为字典
    # 5.返回相应

请求方式和路由
    GET     orders/placeorders/



"""
from rest_framework.permissions import IsAuthenticated
class PlaceOrderAPIView(APIView):

    # 接收用户信息
    # 添加权限
    permission_classes = [IsAuthenticated]

    def get(self,request):
        # 1.接收用户信息, 并验证用户信息
        user = request.user
        # 2.根据用户信息获取redis中选中商品的id  [id,id,id]
        redis_conn = get_redis_connection('cart')

        # hash   {sku_id:count }
        redis_id_counts = redis_conn.hgetall('cart_%s'%user.id)
        # set
        redis_selected_ids = redis_conn.smembers('cart_selected_%s'%user.id)

        # 类型的转换, 在类型转换过程中,我们重新组织(获取)选中的商品的信息

        redis_selected_cart = {}
        # {sku_id:count}
        for sku_id in redis_selected_ids:
            redis_selected_cart[int(sku_id)] = int(redis_id_counts[sku_id])

        ids = redis_selected_cart.keys()
        # 3.根据id获取商品的详细信息 [sku,sku,sku]
        skus = SKU.objects.filter(pk__in=ids)

        for sku in skus:
            sku.count = redis_selected_cart[sku.id]
        # 4.将对象列表转换为字典
        # serializer = CartSKUSerializer(skus,many=True)
        # 5.返回相应

        # 钱
        # 最好使用 货比类型
        from decimal import Decimal

        # 100/3 = 33.33    33.33   33.33  33.34
        freight = Decimal('10.00')

        # data = {
        #     'skus':serializer.data,
        #     'freight':freight
        # }
        # return Response(data)

        serializer = PlaceOrderSerialzier({'freight':freight,
                                           'skus':skus})

        return Response(serializer.data)
"""
[
  {
    "id": 1,
    "name": "Apple MacBook Pro 13.3英寸笔记本 银色",
    "default_image_url": "http://image.meiduo.site:8888/group1/M00/00/02/CtM3BVrPB4GAWkTlAAGuN6wB9fU4220429",
    "price": "11388.00",
    "count": 11
  },
  {
    "id": 10,
    "name": "华为 HUAWEI P10 Plus 6GB+128GB 钻雕金 移动联通电信4G手机 双卡双待",
    "default_image_url": "http://image.meiduo.site:8888/group1/M00/00/02/CtM3BVrRchWAMc8rAARfIK95am88158618",
    "price": "3788.00",
    "count": 1
  }
]

{
    skus: serializer.data,
    运费:10
}


"""

"""
提交订单

需求:
    当用户点击提交按钮的时候,我们需要让前端 将 用户信息, 地址,支付方式 提交给后端

步骤:
    1. 接收数据
    2. 验证数据
    3. 数据入库
    4. 返回相应

请求方式和路由
    POST  orders/

"""

from orders.serializers import OrderSerializer
class OrderAPIView(APIView):

    permission_classes = [IsAuthenticated]

    def post(self,request):

        # 1. 接收数据
        data = request.data
        # 2. 验证数据
        serializer = OrderSerializer(data=data,context={'request':request})
        serializer.is_valid()
        # 3. 数据入库
        serializer.save()
        # 4. 返回相应
        return Response(serializer.data)


# class AllOrderInfo(APIView):
#
#     # 1.判断用户是否登录
#     permission_classes = [IsAuthenticated]
#
#     def get(self,request):
#         # 2.接收参数
#         user = request.user
#         # 3.校验参数
#         orders = OrderInfo.objects.filter(user_id = user.id)
#         # 便利多个查询结果集
#         # for order in orders:
#         #
#         #     # 分别取出 订单的id
#         #     order_id = order.order_id
#         #
#         #     # 根据订单的id来查询所有的  商品订单信息
#         #     goods = OrderGoods.objects.filter(order_id = order_id)
#         #
#         #     # 便利商品信息
#         #     for good in goods:
#         #
#         #         # 获取商品id
#         #         sku_id = good.sku_id
#         #
#         #         # 查询商品
#         #         skus = SKU.objects.get(pk=sku_id)
#         #
#         #         serializer1 = AllGoodsSerializer(instance=skus)
#         #
#         #         data = serializer1.data
#         #
#         #         good.default_image_url = data.get('default_image_url')
#         #
#         #         # default_image_url = data.get('default_image_url')
#         #         # print(default_image_url)
#         #         # # good.id = data.get('id')
#         #         good.name = data.get('name')
#
#             # serializer2 = AllOrderGoodsSerializer(instance=goods,many=True)
#
#             # return Response(serializer2.data)
#
#                 #
#                 # data1 = serializer2.data
#
#                 # good.price = data.get('price')
#
#
#                 # for order1 in orders:
#                 #
#                 #     order1.default_image_url = data.get('default_image_url')
#                 #     order1.id = data.get('id')
#                 #     order1.name = data.get('name')
#                 #     order1.price = data.get('price')
#         # 4.查询数据库
#
#         serializer = AllOrderInfoSerializer(instance=orders, many=True)
#         return Response({
#
#             "results":serializer.data
#
#         })
#         # 5.返回响应

# 使用ListAPIView 获取全部的订单信息
from rest_framework.generics import ListAPIView
class AllOrderInfo(ListAPIView):

    permission_classes = [IsAuthenticated]

    serializer_class = AllOrderInfoSerializer

    def get_queryset(self):

        user = self.request.user

        return OrderInfo.objects.filter(user_id = user.id)



####################################  评论列表进行评论  ###########################################

'''
一.需求分析

二.实现步骤

三.选择路由

四.选择视图

五.书写代码


一.需求分析

    当用户点击去评价时  需要 前端发送 user  订单号order_id  商品sku_id
    查询sku_id  来返回数据

二.实现步骤

    1.登录用户
    2.获取参数
    3.校验参数
    4.查询数据库
    5.返回响应

三.选择路由

    GET   /orders/comment/(?P<sku_id>\d+)/

    (?P<order_id>\d+)/uncommentgoods/

四.选择视图

    APIView

五.书写代码

'''
class SkuCommentAPIView(APIView):

    permission_classes = [IsAuthenticated]


    def get(self,request,order_id):

        # orders = OrderInfo.objects.get(order_id=order_id)

        goods = OrderGoods.objects.filter(order_id=order_id,is_commented=False)

        serializer = AllOrderGoodsSerializer(instance=goods,many=True)

        return Response(serializer.data)

        # serializer = AllOrderInfoSerializer(instance=orders)

        # skus = SKU.objects.filter(pk=sku_id)

        # serializer = SkuCommentSerializer(instance=skus,many=True)

        # return Response(serializer.data)

        # return Response(serializer.data)


##################################  保存评论信息  ###############################################

'''
一.需求分析
二.实现步骤
三.选择视图
四.选择路由
五.书写代码

一.需求分析

    用户进行评论时  需要 前端传递   user order_id  评价内容  满意程度  是否佚名

二.实现步骤
    1.登录
    2.接收参数
    3.校验参数
    4.保存数据
    5.返回响应

三.选择视图

    APIView

四.选择路由

    PUT  /orders/comment/

五.书写代码

'''
class CreateCommentAPIView(APIView):

    # 1.登录
    permission_classes = [IsAuthenticated]

    # 2.接收参数
    def post(self,request,order_id):

        data = request.data

        sku = data.get('sku')
        # 3.校验参数
        # orders = OrderInfo.objects.get(order_id=order_id)
        #
        # # for order in orders:
        #     # 分别取出 订单的id
        #     order_id = orders.order_id

        # 根据订单的id来查询所有的  商品订单信息
        goods = OrderGoods.objects.get(sku_id=sku)
    # 查询数据库

        serializer = CreateCommentSerializer(instance=goods,data=data)

        serializer.is_valid(raise_exception=True)

        serializer.save()

        # 修改 订单的状态

        # 修改 sku的评论个数
        skus = SKU.objects.get(pk=sku)

        data1 = {'comments':'1'}

        serializer1 = SkuUpdateSerializer(instance=skus,data=data1)

        serializer1.is_valid(raise_exception=True)

        serializer1.save()

        # 判断一个订单的商品 状态是否都是 已经是否评价了 在修改订单的 订单状态
        goodss = OrderGoods.objects.filter(order_id=order_id)

        for good in goodss:

            # 如果状态不都是 1 则不修改 订单的状态
            if good.is_commented != True:

                return Response(serializer.data)

        orders = OrderInfo.objects.get(order_id=order_id)

        orders.status = 5

        orders.save()

        return Response(serializer.data)

        # http://api.meiduo.site:8000/orders/20190317040829000000001/payment/
        # 4.保存数据
        # 5.返回响应


##################################  显示评论内容  ##########################################

'''
一.需求分析

二.实现步骤

三.实现路由

四.选择视图

五.书写代码


一.需求分析

    当用户点击 商品详细信息时能够 展示 商品的评论信息
    需要前端传递sku 的id  商品和评论是一对多

二.实现步骤

    1.接收参数
    2.校验参数
    3.查询数据库
    4.返回响应

三.实现路由

    GET   /orders/skus/(?P<id>\d+)/comments

四.选择视图



五.书写代码
'''


class SkuCommentsAPIView(APIView):

    def get(self, request, id):

        goods = OrderGoods.objects.filter(sku=id)

        serializer = CommentOrderGoodsSerializer(instance=goods,many=True)

        return Response(serializer.data)